`
https://leetcode.cn/problems/maximum-length-substring-with-two-occurrences/
`

/**
 * @param {string} s
 * @return {number}
 */
var maximumLengthSubstring = function (s) {
  const n = s.length
  let res = 0
  const { get, set } = counter()
  let left = 0, right = 0

  while (right < n) {
    const c = s[right++]
    set(c, get(c) + 1)

    // 每个字符最多出现两次，当前窗口扩大时更新答案
    if (get(c) <= 2) res = Math.max(res, right - left)

    // 有字符出现超过两次，缩减窗口直到该字符不超过两次
    while (get(c) > 2) {
      const d = s[left++]
      set(d, get(d) - 1)
    }
  }

  return res
};

function counter() {
  const cnt = new Array(26).fill(0)
  const ordA = 'a'.charCodeAt(0)
  return {
    get(c) {
      return cnt[c.charCodeAt(0) - ordA]
    },
    set(c, val) {
      cnt[c.charCodeAt(0) - ordA] = val
    }
  }
}